package com.zzh.custom.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

import com.zzh.custom.R;
import com.zzh.tools.listener.ToolOnClickListener;
import com.zzh.tools.utils.ToolLog;


/**
 * @author zhangzhihao
 * @email zhangzhihao@gongjiangren.net
 * @date 2021-02-02
 * @desc 跟随软键盘评论编辑
 */
public class CommentsDialog extends DialogFragment {

    // TODO: 2021-02-06 是不是需要添加记忆功能 待定 

    public interface OnSendClickListener {
        void onSend(String value);
    }

    public interface OnKeyInputListener {
        void onShow(int height);

        void onHide();
    }

    public interface OnCommentsEditLocationListener {
        void onHeightChange(int height, int top, int bottom);
    }

    private AppCompatActivity mActivity;
    private Fragment mFragment;

    private String promptTextStr;
    private String textStr;

    private OnSendClickListener mOnSendClickListener;

    private OnKeyInputListener mOnKeyInputListener;

    private OnCommentsEditLocationListener mOnCommentsEditLocationListener;

    private boolean mIsHideKeyClose;


    public CommentsDialog() {
    }


    private CommentsDialog(AppCompatActivity activity) {
        this.mActivity = activity;
    }

    private CommentsDialog(Fragment fragment) {
        this.mFragment = fragment;
    }

    private View mRootView;
    private EditText mEditText;
    private Button mSend;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.comments_dialog, null, false);
            initView(mRootView);
            setClick();
        }
        config();
        return mRootView;
    }


    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setDimAmount(0.0f);
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {
        mEditText = view.findViewById(R.id.edit);
        mSend = view.findViewById(R.id.send);
    }

    // 软键盘的高度
    private int mKeyInputHeight = 0;
    // 是不是显示过软键盘 只要显示过就是true
    private boolean mIsPopUpKeyInput = false;
    // 当前软键盘是不是显示状态 true false
    private boolean mIsShowKeyInput = false;

    private void setClick() {
        mSend.setOnClickListener(new ToolOnClickListener() {
            @Override
            public void onClick(View v) {
                super.onClick(v);
                if (id == -1) {
                    return;
                }
                dismiss();
                if (mOnSendClickListener != null) {
                    mOnSendClickListener.onSend(mEditText.getText().toString());
                    mEditText.setText("");
                }
                closeInput();
            }
        });
        mRootView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                closeInput();
                if (!mIsHideKeyClose) {
                    dismiss();
                }
            }
            return true;
        });
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO: 2021-02-02 执行发送按钮点击状态替换

            }
        });
        mEditText.getViewTreeObserver().addOnGlobalLayoutListener(() -> mEditText.postDelayed(() -> keyStatus(), 100));
    }


    private void keyStatus() {
        Window window = getActivity().getWindow();
        if (window == null) {
            return;
        }
        View decorView = window.getDecorView();
        Rect r = new Rect();
        //获取当前界面可视部分
        decorView.getWindowVisibleDisplayFrame(r);
        //获取屏幕的高度
        int screenHeight = decorView.getRootView().getHeight();
        //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
        mKeyInputHeight = screenHeight - r.bottom;
        if (mIsPopUpKeyInput) {
            if (mIsShowKeyInput && mKeyInputHeight == 0) {
                mIsShowKeyInput = false;
                if (mOnKeyInputListener != null) {
                    mOnKeyInputListener.onHide();
                }
                if (mIsHideKeyClose) {
                    // 隐藏软键盘
                    dismiss();
                }
            } else if (!mIsShowKeyInput && mKeyInputHeight > 0) {
                mIsShowKeyInput = true;
                // 显示软键盘
                if (mOnKeyInputListener != null) {
                    mOnKeyInputListener.onShow(mKeyInputHeight);
                }
            } else {
                // 其他操作
                ToolLog.i("zzh", "》》》其他操作》》");
            }
            if (mOnCommentsEditLocationListener != null) {
                int editHeight = mEditText.getHeight();
                mOnCommentsEditLocationListener.onHeightChange(editHeight, mKeyInputHeight + editHeight, mKeyInputHeight);
            }
        }
        if (!mIsPopUpKeyInput && mKeyInputHeight > 0) {
            mIsPopUpKeyInput = true;
            mIsShowKeyInput = true;
            // 显示软键盘
            if (mOnKeyInputListener != null) {
                mOnKeyInputListener.onShow(mKeyInputHeight);
            }
            if (mOnCommentsEditLocationListener != null) {
                int editHeight = mEditText.getHeight();
                mOnCommentsEditLocationListener.onHeightChange(editHeight, mKeyInputHeight + editHeight, mKeyInputHeight);
            }
        }
    }

    /**
     * 配置显示数据
     */
    private void config() {
        configDialog();
        if (!TextUtils.isEmpty(promptTextStr)) {
            mEditText.setHint(promptTextStr);
        }
        if (!TextUtils.isEmpty(textStr)) {
            mEditText.setText(textStr);
            mEditText.setSelection(mEditText.getText().length());
        }
        mEditText.postDelayed(() -> showInput(mEditText), 100);
    }

    private void showInput(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    private void closeInput() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }


    private void configDialog() {
        Dialog dialog = getDialog();
        dialog.setOnKeyListener((dialog1, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                dismiss();
                return true;
            }
            return false;
        });
    }

    public void show(@NonNull String dialogName) {
        show(mActivity == null ? mFragment.getChildFragmentManager() : mActivity.getSupportFragmentManager(), dialogName);
    }

    public static class Builder {

        /**
         * 提示文案
         */
        private String promptTextStr;
        /**
         * 编辑之后的文本
         */
        private String textStr;

        /**
         * 发送事件
         */
        private OnSendClickListener mOnSendClickListener;

        /**
         * 软键盘监听
         */
        private OnKeyInputListener mOnKeyInputListener;

        /**
         * 编辑框变化监听
         */
        private OnCommentsEditLocationListener mOnCommentsEditLocationListener;

        /**
         * 是不是销毁软键盘是隐藏编辑框
         */
        private boolean mIsHideKeyClose = true;

        public Builder setOnSendClickListener(OnSendClickListener onSendClickListener) {
            this.mOnSendClickListener = onSendClickListener;
            return this;
        }

        public Builder setPromptTextStr(String promptTextStr) {
            this.promptTextStr = promptTextStr;
            return this;
        }

        public Builder setTextStr(String textStr) {
            this.textStr = textStr;
            return this;
        }

        public Builder setOnKeyInputListener(OnKeyInputListener onKeyInputListener) {
            this.mOnKeyInputListener = onKeyInputListener;
            return this;
        }

        public Builder setOnCommentsEditLocationListener(OnCommentsEditLocationListener onCommentsEditLocationListener) {
            this.mOnCommentsEditLocationListener = onCommentsEditLocationListener;
            return this;
        }

        public Builder setIsHideKeyClose(boolean isHideKeyClose) {
            this.mIsHideKeyClose = isHideKeyClose;
            return this;
        }

        private CommentsDialog create(AppCompatActivity appCompatActivity, Fragment fragment) {
            CommentsDialog commentsDialog = appCompatActivity == null ? new CommentsDialog(fragment) : new CommentsDialog(appCompatActivity);
            commentsDialog.promptTextStr = promptTextStr;
            commentsDialog.textStr = textStr;
            commentsDialog.mOnSendClickListener = mOnSendClickListener;
            commentsDialog.mOnKeyInputListener = mOnKeyInputListener;
            commentsDialog.mOnCommentsEditLocationListener = mOnCommentsEditLocationListener;
            commentsDialog.mIsHideKeyClose = mIsHideKeyClose;
            return commentsDialog;
        }

        public CommentsDialog create(AppCompatActivity appCompatActivity) {
            return create(appCompatActivity, null);
        }

        public CommentsDialog create(Fragment fragment) {
            return create(null, fragment);
        }
    }

}
